package controller

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"git.oschina.net/864233002/CloudServer/models"
	jwt "github.com/dgrijalva/jwt-go"
	"time"
)

type User struct {
	Base
}

func (this User) NextPre() {
	//	fmt.Fprint(this.ResponseWriter, "NextPre")
}

func (this User) ActionHello() {
	fmt.Fprint(this.ResponseWriter, "Hello Go !")
}

//用户创建
func (this User) ActionCreate() {

}

//用户登录
type Userinfo struct {
	Id         uint64
	Guid       string
	Phone      string
	Realname   string
	Spell      string
	Gender     int8
	IdCard     string
	Picture    string
	SchoolGuid string
	CreateTime string
}

func (this User) ActionLogin() {

	phone := this.GetStringPostParam("phone")
	password := this.GetStringPostParam("password")
	tmp_pwd := md5.Sum([]byte(password))
	md5_pwd := hex.EncodeToString(tmp_pwd[:])
	var user_model models.Users
	user_model.Phone = phone
	user_model.Password = md5_pwd
	user_model.LoginCheck()

	if user_model.Id != 0 {

		var userinfo Userinfo
		userinfo.Id = user_model.Id
		userinfo.Guid = user_model.Guid
		userinfo.Phone = user_model.Phone
		userinfo.Realname = user_model.Realname
		userinfo.Spell = user_model.Spell
		userinfo.Gender = user_model.Gender
		userinfo.IdCard = user_model.IdCard
		userinfo.Picture = user_model.Picture
		userinfo.SchoolGuid = user_model.SchoolGuid
		userinfo.CreateTime = user_model.CreateTime.Format("2009-10-01 09:00:00")

		// Create the token
		token := jwt.New(jwt.GetSigningMethod("RS256"))
		token.Claims["userinfo"] = userinfo
		expires := time.Now().Add(time.Hour * 72).Unix()
		token.Claims["exp"] = expires
		// Sign and get the complete encoded token as a string
		tokenString, err := token.SignedString(SignKey)
		data := make(map[string]interface{})
		if err == nil {
			data["token"] = tokenString
			data["expires"] = expires
			data["userinfo"] = userinfo
			this.AjaxReturnFun(1, "success", data)
		} else {
			this.AjaxReturnFun(0, "令牌无法生成!"+err.Error(), nil)
		}

	} else {
		this.AjaxReturnFun(0, "用户不存在!", nil)
	}
}

//获取登录用户信息,验证token是否有效
func (this User) ActionLoginInfo() {
	if TokenStatus == TokenPass {
		this.AjaxReturnFun(1, "success", LoginUserInfo)
	} else if TokenStatus == TokenExpired {
		this.AjaxReturnFun(-1, "token 过期", nil)
	} else {
		this.AjaxReturnFun(-2, "token 验证失败", nil)
	}
}
